package com.praveen.twu.managers;

import com.praveen.twu.item.Book;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by praveen on 20/6/14.
 */
public class BookManager {

    private static List<Book> books = new ArrayList<Book>();
    private static List<Book> checkedout = new ArrayList<Book>();

    public static List<Book> getAvailableBookList() {
        return books;
    }

    public static void populate() {
        books.clear();
        books.add(new Book("1000", "Harry Potter", "J. K. Rowling", 1997));
        books.add(new Book("1001", "A Game of Thrones", "George R. R. Martin", 1996));
        books.add(new Book("1010", "Journey to the center of the Earth", "Jules Verne", 1864));
        books.add(new Book("1011", "Treasure Island", "R. L. Stevenson", 1883));
    }

    public static boolean bookAvailable(String id) {
        for (Book b : books)
            if (b.getIsbn().equals(id))
                return true;
        return false;
    }

    private static Book switchState(List<Book> from, List<Book> to, String id) {
        for (Book b : from)
            if (b.getIsbn().equals(id)) {
                to.add(b);
                from.remove(b);
                return b;
            }
        return null;
    }

    public static Book checkout(String id) {
        if (!bookAvailable(id) || !LoginManager.isLoggedIn())
            return null;
        return switchState(books, checkedout, id);
    }

    public static Book returnBook(String id) {
        if (bookAvailable(id) || !LoginManager.isLoggedIn())
            return null;
        return switchState(checkedout, books, id);
    }
}